package com.example.ymm.modules1.service.dd.ms;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalktodo_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSetting;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.entity.my.user.DbUserWait;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.ServletUtils;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DingWaitService {

    @Autowired
    AccessTokenH5Service2 accessTokenH5Service;

    @Autowired
    AccessTokenOaAppService accessTokenOaAppService;

    @Autowired
    DbUserService dbUserService;
    /**
     * 二次开发系统通知
     */

    @Value("${dd_h5.agentId}")
    private Long agentId;

    @Value("${dd_h5.appId}")
    String appId;

    @Value("${dd_h5.corpid}")
    String corpid;

    @Value("${oa_app.appId}")
    String oa_appId;

    @Value("${oa_app.corpid}")
    String oa_corpid;

    public static com.aliyun.dingtalktodo_1_0.Client createClient()  {
        try {
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
            config.protocol = "https";
            config.regionId = "central";
            return new com.aliyun.dingtalktodo_1_0.Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



    /**
     * 创建 代办
     * @param wait
     * @param approvalSetting 页面路径 /yw/ywApproveList2
     * @throws Exception
     */
    public JSONObject createTodo(DbUserWait wait, SysApprovalSetting approvalSetting, String description) {
        String page=approvalSetting.getPage();
        JSONObject jsonObject=null;

        String url="http://220.161.77.66:10111/#/h5Login?redirect="+page;
        String encode= ServletUtils.urlEncode(url);
        String message_url= "dingtalk://dingtalkclient/action/openapp?corpid="+corpid+"&container_type=work_platform&app_id="+appId+"&redirect_type=jump&redirect_url="+encode;//&redirect_url=/h5Login
        String accessToken = accessTokenH5Service.getAccessToken();
        if(approvalSetting.getApprovalSettingId().equals("3")){
            accessToken =accessTokenOaAppService.getAccessToken();
            url="http://220.161.77.66:10111/oa_app/#/pages/kq/approve/list";
            encode= ServletUtils.urlEncode(url);
            message_url= "dingtalk://dingtalkclient/action/openapp?corpid="+corpid+"&container_type=work_platform&app_id="+oa_appId+"&redirect_type=jump&redirect_url="+encode;
        }
        DbUser dbUser = dbUserService.findByUserId(wait.getUserId());
        DbUser createUserName = dbUserService.findByUserName(wait.getCreateUserName());

        com.aliyun.dingtalktodo_1_0.Client client  =createClient();

        CreateTodoTaskHeaders createTodoTaskHeaders = new CreateTodoTaskHeaders();
        createTodoTaskHeaders.xAcsDingtalkAccessToken = accessToken;
        CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs notifyConfigs = new CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs()
                .setDingNotify("1");
        CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl detailUrl = new CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl()
                .setAppUrl(message_url)
                .setPcUrl(message_url);
        List<String> executorIdArrs=new ArrayList<>();
        executorIdArrs.add(dbUser.getUnionid());

        CreateTodoTaskRequest createTodoTaskRequest = new CreateTodoTaskRequest()
                .setSourceId(wait.getId())
                .setCreatorId(createUserName.getUnionid())
                .setDescription(description)
                .setSubject(wait.getPage()+wait.getApproveNo()+"待处理!")
                .setDescription(wait.getCreateUserName())
                .setExecutorIds(executorIdArrs)
                .setDetailUrl(detailUrl)
                .setIsOnlyShowExecutor(false)
                .setPriority(40)
                .setNotifyConfigs(notifyConfigs);
        try {
            CreateTodoTaskResponse createTodo = client.createTodoTaskWithOptions(dbUser.getUnionid(), createTodoTaskRequest, createTodoTaskHeaders, new RuntimeOptions());
            jsonObject = JSONObject.parseObject(JSONObject.toJSONString(createTodo.getBody()));

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.code);
                System.out.println(err.message);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.code);
                System.out.println(err.message);
            }
        }
        return jsonObject;
    }


    /**
     * 更新待办任务 为完成
     * @return
     */
    public JSONObject finishTodo(DbUserWait wait){
        JSONObject jsonObject=null;
        if(UtilValidate.isEmpty(wait.getDdWaitId())){
            return jsonObject;
        }
        DbUser dbUser = dbUserService.findByUserId(wait.getUserId());

        com.aliyun.dingtalktodo_1_0.Client client = createClient();
        UpdateTodoTaskExecutorStatusHeaders updateTodoTaskExecutorStatusHeaders = new UpdateTodoTaskExecutorStatusHeaders();
        updateTodoTaskExecutorStatusHeaders.xAcsDingtalkAccessToken = accessTokenH5Service.getAccessToken();
        UpdateTodoTaskExecutorStatusRequest.UpdateTodoTaskExecutorStatusRequestExecutorStatusList executorStatusList0 = new UpdateTodoTaskExecutorStatusRequest.UpdateTodoTaskExecutorStatusRequestExecutorStatusList()
                .setId(dbUser.getUnionid())
                .setIsDone(true);
        UpdateTodoTaskExecutorStatusRequest updateTodoTaskExecutorStatusRequest = new UpdateTodoTaskExecutorStatusRequest()
                .setExecutorStatusList(java.util.Arrays.asList(
                        executorStatusList0
                ));
        try {
            UpdateTodoTaskExecutorStatusResponse updateTodo = client.updateTodoTaskExecutorStatusWithOptions(dbUser.getUnionid(), wait.getDdWaitId(), updateTodoTaskExecutorStatusRequest, updateTodoTaskExecutorStatusHeaders, new RuntimeOptions());

            jsonObject = JSONObject.parseObject(JSONObject.toJSONString(updateTodo.getBody()));

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }finally {
            return jsonObject;
        }
    }


}
